package Server.Sessions;

import java.util.Iterator;

import shared.Messages.BeginMessage;
import shared.Messages.DcWinMessage;
import shared.Messages.MoveMessage;
import shared.Messages.QuestionMessage;
import shared.Messages.TurnMessage;
import shared.Messages.WinMessage;



public class Broadcaster extends Thread {
	private ActiveSessions activeSessions;
	private OutboundMessages outQueue;


	public Broadcaster(ActiveSessions aa, OutboundMessages o) {
		activeSessions = aa;
		outQueue = o;
		start();
	}

	public void run() {
		while (true) {
			Object s = outQueue.getMessage();// blocked
			synchronized (activeSessions) { // ActiveSessions lukku!
				Iterator<ClientSession> active = activeSessions.iterator();

				while (active.hasNext()) {
					ClientSession cli = active.next();

					if (!cli.isAlive()) {
						active.remove();
					} else if (s == null) {
						break;
					}else if(s instanceof BeginMessage){
						if(cli.p.GameNo == ((BeginMessage)s).GameNo){
							cli.sendMessage((BeginMessage)s);
						}
					}else if(s instanceof MoveMessage){
						if(cli.p.GameNo == ((MoveMessage)s).GameNo){
							cli.sendMessage((MoveMessage)s);
						}
					}else if(s instanceof TurnMessage){
						if(cli.p.GameNo == ((TurnMessage)s).GameNo){
							cli.sendMessage((TurnMessage)s);
						}
					}else if(s instanceof QuestionMessage){
						if(cli.p.GameNo == ((QuestionMessage)s).GameNo){
							if(cli.p.playerID == ((QuestionMessage)s).playerId){
								cli.sendMessage((QuestionMessage)s);
							}
						}
					}else if(s instanceof WinMessage){
						if(cli.p.GameNo == ((WinMessage)s).GameNo){
							cli.sendMessage((WinMessage)s);
						}
					}else if(s instanceof DcWinMessage){
						if(cli.p.GameNo == ((DcWinMessage)s).GameNo){
							cli.sendMessage((DcWinMessage)s);
						}
					}
				}
			}	
		}
	}
}